import * as path from 'path';
import * as fs from 'fs';
//获取当前模块的目录路径	
const root = path.resolve();
/**
 * 处理POST请求
 * @param req {http.IncomingMessage} 请求对象
 * @param res {http.ServerResponse} 响应对象
*/
export function POST(req, res) {
	const chunks = [];
	req.on('data', chunk => chunks.push(chunk));
	req.on('end', () => {
		const dataBuffer = Buffer.concat(chunks);
		const handlers = {
			'/json': handleJsonData,
			'/binaryUpload': handleBinaryUpload,
			'/formDataUpload': handleFormDataUpload
		};

		const handler = handlers[req.url];
		if (!handler) {
			res.writeHead(404, { 'Content-Type': 'text/plain;charset=utf-8' });
			res.end('404,没有这个接口!');
		} else {
			handler(req, dataBuffer, res);
		}
	});
};

function handleJsonData(req, dataBuffer, res) {
	const jsonData = JSON.parse(dataBuffer.toString() || "{}");
	console.log(jsonData);
	res.writeHead(200, { 'Content-Type': 'application/json' });
	res.end(dataBuffer);
}

function handleBinaryUpload(req, dataBuffer, res) {
	const fileName = `file_${Date.now()}.${req.headers['x-ext']}`;
	writeFile(fileName, dataBuffer);
	res.writeHead(200, { 'Content-Type': 'application/json' });
	res.end(JSON.stringify({ code: 200, msg: 'ok' }));
}

function handleFormDataUpload(req, dataBuffer, res) {
	// 获取并验证 boundary
	const boundaryMatch = req.headers['content-type']?.match(/boundary=(?:"([^"]+)"|([^;]+))/i);
	const boundary = `--${boundaryMatch[1] || boundaryMatch[2]}`;
	// 将 boundary 转换为 Buffer
	const boundaryBuffer = Buffer.from(boundary);
	// 数据切块
	const parts = [];
	let start = 0;
	let end = 0;
	while ((end = dataBuffer.indexOf(boundaryBuffer, start)) !== -1) {
		if (end > start) {
			parts.push(dataBuffer.subarray(start, end));
		}
		start = end + boundaryBuffer.length;
	}
	// 处理解析后的数据
	for (const part of parts) {
		// 查找头部结束位置
		const headerEndIndex = part.indexOf('\r\n\r\n');
		// 获取头部信息
		const info = part.subarray(0, headerEndIndex).toString('utf-8');
		// 获取内容部分，跳过 \r\n\r\n,移除末尾的 \r\n
		const content = part.subarray(headerEndIndex + 4, part.length - 2);
		// 提取文件名和名字信息
		const filename = info.match(/filename="([^"]+)"/)?.[1];
		const name = info.match(/name="([^"]+)"/)?.[1];
		// 处理数据
		if (filename) {
			writeFile(filename, content);
		} else {
			if (name) {
				console.log('FormData', name, content.toString('utf-8'));
			}
		}

	}
	res.writeHead(200, { 'Content-Type': 'application/json' });
	res.end(JSON.stringify({ code: 200, msg: 'ok' }));
}

/**
 * 写入文件
 * @param fileName {string} 文件名
 * @param fileContent {Buffer} 文件内容
*/
function writeFile(fileName, fileContent) {
	//创建文件夹路径
	const folderPath = path.join(root, 'uploads');
	// 拼接文件的完整路径
	const filePath = path.join(root, 'uploads', fileName);
	// 判断文件夹是否存在
	if (!fs.existsSync(folderPath)) {
		// 如果文件夹不存在，创建它
		fs.mkdirSync(folderPath);
	}
	fs.writeFileSync(filePath, fileContent);
	console.log('File saved successfully:', filePath);
}
